﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Model.Core;
using Models;
using Newtonsoft.Json;
using SIE.SCADA.Common.Log;
using SIE.SCADA.Helper;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo;
using SIE.SCADA.ZemtDemo.Common;
using SIE.SCADA.ZemtDemo.MqClient.Model;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 设备数据上报
    /// </summary>
    public class EquipmentDataManager : MqMangerBase<EquipmentDataManager>
    {
        //private scada_product_info _Disid_T;
        public string line_names = Env.LineName.Value;
        public string LineGroupName = Env.LineGroupName.Value;
        private readonly string IfaceName = "EPMDATATOSCE"; //接口名称
        private readonly string EXCHANAGE = "ZEMT_MQ_EXCHANGE_EPMDATATOSCE";
        private readonly string ROUTEKEY = "EPMDATATOSCE_SIE";
        private AdvancedThread thread;

        //修改状态，请求上传配置信息
        public void CheckUpload(List<scada_product_info> products)
        {


            foreach (var product in products)
            {


                if (product != null)
                {
                    System.TimeSpan t1 = (System.TimeSpan)(System.DateTime.Now - product.modifytime_dt);
                    double timespan2 = 0;
                    if (t1 != null)
                    {
                        timespan2 = t1.TotalSeconds;
                    }
                    ;
                    if (timespan2 > 120)
                    {

                        List<scada_jobstep_record> jobsteps = QueryData.GetJobStepByProdID(product.id);
                        if (jobsteps==null || jobsteps.Count==0) {
                            continue;
                        }
                        List<EquipData> equipdatas = new List<EquipData>();
                        foreach (var jobstep in jobsteps) {
                            EquipData equipData = new EquipData();
                            equipData.vinnum = jobstep.vinnum;
                            equipData.step = jobstep.step.ToString();
                            equipData.torque = jobstep.torque?.ToString();
                            equipData.torqueunit = "N.m";
                            equipData.torquestatus = jobstep.torquestatus.ToString();
                            equipData.torquestatusDesc = jobstep.torquestatus==0?"不合格" : "合格";
                            equipData.angle = jobstep.angle?.ToString();
                            equipData.angleunit = "度";
                            equipData.anglestatus = jobstep.anglestatus.ToString();
                            equipData.anglestatusDesc = jobstep.anglestatus == 0 ? "不合格" : "合格";
                            equipData.TighteningStatus = jobstep.TighteningStatus.ToString();
                            equipData.TighteningStatusDesc = jobstep.TighteningStatus == 0 ? "不合格" : "合格";
                            equipData.batchstatus = jobstep.batchstatus.ToString(); ;
                            equipData.batchcounter = jobstep.batchcounter;
                            equipData.batchsize = jobstep.batchsize?.ToString();
                            equipData.comment = jobstep.comment_str;
                            equipData.createtime = jobstep.createtime_dt.ToString("yyyy/MM/dd HH:mm:ss");
                            
                            equipdatas.Add(equipData);


                        }

                        

                        
                       

                        EqData eqData = new EqData();
                        //eqData.equipmentId = "";
                        eqData.equipmentType = "TW";
                        eqData.recordType = product.processtype;//补打 新打 还有监造重打     
                        eqData.matId = product.matid;
                        eqData.repairPross = product.repaircode;
                        eqData.pono = product.poid;
                        eqData.serialNo = product.serial_number;
                        eqData.batch = "";
                        eqData.disNo = "";
                        eqData.workStartTime = product.createtime_dt?.ToString("yyyy/MM/dd HH:mm:ss");
                        eqData.workFinishTime = product.modifytime_dt?.ToString("yyyy/MM/dd HH:mm:ss");
                        //eqData.workId = "";

                        eqData.equipmentId = product.equipmentid;                     
                        
                        eqData.workId = product.userid;

                        eqData.equipdatas = equipdatas;
                        List<EqData> equiMdatas = new List<EqData>();
                        equiMdatas.Add(eqData);
                        EquipmentData senddata = new EquipmentData();
                        senddata.equiMdatas = equiMdatas;
                        var jsonData = JsonConvert.SerializeObject(senddata);
                        //Logger.Info("发送设备数据 -> SCE，" + jsonData);
                        bool sendResult = Send(senddata);
                        if (sendResult)
                        {
                            //将工件状态改为“已上报”
                            SubmitDB.UpdateProductInfoToFinish(product.id);
                        }
                    }
                }
            }



        }

        //上报请求
        bool Send(EquipmentData senddata)
        {
            var res = mqhelper.TopicExchangePublish(senddata, EXCHANAGE, "", $"{IfaceName}.{LineGroupName}"
                , true, false, true, false);
            if (res.Success)
            {
                System.Diagnostics.Debug.WriteLine("数据已推送完成的！");
                return true;
            }
            else
            {
                return false;
            }
        }

        private void Loop()
        {
            var pgsql = new PgSqlAccess();
            using (var ctx = pgsql.GetClient())
            {
                if (pgsql.DBClient is SmdcOrmClient ormClient)
                {
                    var upload = ormClient.SqlSugarClient.Queryable<scada_product_info>().Where(m => m.state_int == (int)State.Finish && m.modifytime_dt != null && m.userid !=null).ToList();
                    CheckUpload(upload);
                }
            }
        }

        /// <summary>
        /// KJF 20210329 新增
        /// 手动上报
        /// </summary>
        public void PostEquipmentDataByWorkID(string workID, string SN)
        {
            var pgsql = new PgSqlAccess();
            using (var ctx = pgsql.GetClient())
            {
                if (pgsql.DBClient is SmdcOrmClient ormClient)
                {
                    var upload = ormClient.SqlSugarClient.Queryable<scada_product_info>().Where(m => m.disidno == workID
                    && m.serial_number == SN && (m.state_int == (int)State.Finish || m.state_int == (int)State.UploadFinish)).ToList();
                    CheckUpload(upload);
                }
            }
        }


        public void PostEquipmentData(int id)
        {
            var pgsql = new PgSqlAccess();
            using (var ctx = pgsql.GetClient())
            {
                if (pgsql.DBClient is SmdcOrmClient ormClient)
                {
                    var upload = ormClient.SqlSugarClient.Queryable<scada_product_info>().Where(m => m.id == id && (m.state_int == (int)State.Finish || m.state_int == (int)State.UploadFinish)).ToList();
                    CheckUpload(upload);
                }
            }
        }

        public override void Start()
        {
            DataReceive();
            thread = new AdvancedThread(Loop, 60 * 1000);
            thread.Start();
        }

        public override void Stop()
        {
            thread.Stop();
            base.Stop();
        }

        void DataReceive()
        {
            //上报接口
            var res1 = mqhelper.TopicExchangeConsumer<BackResult>((data) =>
            {
                if (data.retcode.Equals("1"))
                {
                    //SaveResult(data);
                    System.Diagnostics.Trace.WriteLine("SCE -> <设备数据>接收成功");
                }
                return true;
            }, EXCHANAGE, $"ZEMT_MQ_SIE_{IfaceName}.{LineGroupName}", $"{ROUTEKEY}.{LineGroupName}", true, false, true, false);


        }

        //void SaveResult(BackResult WorkReportReceiveData)
        //{

        //    if (WorkReportReceiveData != null)
        //    {
        //        if (WorkReportReceiveData.retdatas != null)
        //        {
        //            foreach (var item in WorkReportReceiveData.retdatas)
        //            {
        //                if (item.errormsg.Contains("上报成功"))
        //                {
        //                    SubmitDB.UpdateWoInfoToFinishByWorkNoAndSN(item.disid, item.worksn);
        //                }
        //            }
        //        }
        //    }

        //    Logger.Info("从MES收到上报应答消息！");
        //}





        public class EquipmentData
        {
            /// <summary>
            /// 
            /// </summary>
            public List<EqData> equiMdatas { get; set; }
        }

        public class EqData
        {
            public string equipmentId { get; set; }
            public string equipmentType { get; set; }
            public string recordType { get; set; }
            public string matId { get; set; }
            public string repairPross { get; set; }
            public string pono { get; set; }
            public string serialNo { get; set; }
            public string batch { get; set; }
            public string disNo { get; set; }
            public string workStartTime { get; set; }
            public string workFinishTime { get; set; }
            public string workId { get; set; }

            public List<EquipData> equipdatas { get; set; }
        }

        public class EquipData
        {
            public string vinnum { get; set; }
            public string step { get; set; }
            public string torque { get; set; }
            public string torqueunit { get; set; }
            public string torquestatus { get; set; }
            public string torquestatusDesc { get; set; }
            public string angle { get; set; }
            public string angleunit { get; set; }
            public string anglestatus { get; set; }
            public string anglestatusDesc { get; set; }
            public string TighteningStatus { get; set; }
            public string TighteningStatusDesc { get; set; }
            public string batchstatus { get; set; }
            public string batchcounter { get; set; }
            public string batchsize { get; set; }
            public string comment { get; set; }
            public string createtime { get; set; }

        }







        public class Retdatas
        {

            public string disid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string matid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string worksn { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string errormsg { get; set; }
        }

        public class BackResult
        {
            /// <summary>
            /// 
            /// </summary>
            public string retcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string retmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<Retdatas> retdatas { get; set; }
        }

    }
}
